package com.baidu.aip;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.util.Base64Util;
import com.baidu.aip.util.FileUtil;
import com.baidu.aip.util.HttpUtil;


/**
 * 动漫画人物
 */
public class Selfie_anime {
    public static String selfie_anime(String filePath, String accessToken) {
        String url = "https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime";
        try {
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void savePicture(byte[] b, String savePath) {
        try {
            OutputStream out = new FileOutputStream(savePath);
            out.write(b);
            out.flush();
            out.close();
        } catch (IOException e){
        }
    }

    public static void main(String[] args) {
        String token = AuthService.getAuth();
        System.out.println(token);
        String filePath = "C:\\D\\Python36\\WorkSpace\\XMXMXMXMXM\\BaiDu-Aip\\luer.jpg";
        //String savePath = "C:\\D\\Python36\\WorkSpace\\XMXMXMXMXM\\BaiDu-Aip\\luerDM.jpg";
        String savePath = "C:\\D\\luerDM.jpg";
        String accessTokenJsonStr = Selfie_anime.selfie_anime(filePath, token);

        //Json字符串转Json对象
        JSONObject accessTokenJsonObject = JSONObject.parseObject(accessTokenJsonStr);
        String imageStr = accessTokenJsonObject.getString("image");
        //System.out.println("获取：" + accessTokenJsonStr + "\n" + imageStr + "\n\n");

        byte[] b = Base64Util.decodeAndSave(imageStr);
        savePicture(b, savePath);
    }
}
